<!--  -->
<template>
  <div>
    <div class="  text-slate-400 ">【评分分布】</div>
    <div ref="target" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  data: Array,
});
// console.log("props:", props);
let chart = null;
const target = ref(null);

onMounted(() => {
  chart = echarts.init(target.value);
  ChartInit(); // 将 chart 传递给 ChartInit 函数
});

const ChartInit = () => {
  if (!props.data || props.data.length === 0) {
    console.log("No data to display");
    return;
  }
  const ratingCount = props.data.reduce((acc, item) => {
    if (item !== undefined && item !== null) {
      acc[item] = (acc[item] || 0) + 1;
    }
    return acc;
  }, {});

  // 提取统计结果
  const yAxisData = Object.keys(ratingCount).sort();
  const option = {
    xAxis: {
      type: "category",
      data: yAxisData,
      axisLabel: {
        color: "#9eb1c8",
      },
    },
    yAxis: {
      type: "value",
      show: false,
      max: function (value) {
        return parseInt(value.max * 1.2);
      },
    },
    grid: {
      top: 20,
      right: 0,
      bottom: 20,
      left: -20,
      containLabel: true,
    },
    series: [
      {
        type: "bar",
        data: Object.values(ratingCount),
        itemStyle: {
          color: "#5D98CE",
          borderRadius: 5,
          shadowColor: "rgba(0, 0, 0, 0.3)",
          shadowBlur: 5,
        },
        barWidth: 12,
        label: {
          show: true,
          position: "top",
          color: "#fff",
        },
      },
    ],
  };
  chart.setOption(option);
};
watch(() => props.data, ChartInit);
</script>

<style scoped></style>
